import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:mfkb/config/Config.dart';
import 'package:mfkb/pages/modules/CustomRoute.dart';
import 'package:mfkb/pages/school/AroundPage.dart';
import 'package:mfkb/pages/school/SchoolRelation.dart';
import 'package:mfkb/pages/school/market/SchoolMarket.dart';
import 'package:mfkb/pages/web/WebViewByUrl.dart';
import 'package:mfkb/plugin/MyBehavior.dart';
import 'package:mfkb/service/SchoolService.dart';
import 'package:toast/toast.dart';

import 'package:crypto/crypto.dart';
import 'package:convert/convert.dart';

class School extends StatefulWidget {
  @override
  _SchoolState createState() => _SchoolState();
}

class _SchoolState extends State<School> {

  List list = [
    {"img":""}
  ] ;
  dynamic data ;

  @override
  void initState() {
    super.initState();
    if(Config().getSpf().getString("schoolMd5") == null || Config().getSpf().getString("schoolMd5") == ""){
      download() ;
    }else{
      if(!Config().school){
        SchoolService().checkSchool().then((value){
          if(value["code"] == 200){
            Config().school = true ;
            if(Config().getSpf().getString("schoolMd5") == value["data"]){
              loadResource() ;
            }else{
              download() ;
            }
          }else{
            loadResource() ;
          }
        }) ;
      }else{
        loadResource() ;
      }
    }
  }

  loadResource(){
    String d = Config().getSpf().getString("schoolInit") ;
    dynamic value = jsonDecode(d) ;
    list = jsonDecode(value["banners"]) ;
    data = jsonDecode(value["dynamic"]) ;
    setState(() {});
  }

  download(){
    SchoolService().init().then((value){
      if(value["code"] == 200){
        print(value) ;
        Config().getSpf().setString("schoolInit", jsonEncode(value["data"])) ;
        list = jsonDecode(value["data"]["banners"]) ;
        data = jsonDecode(value["data"]["dynamic"]) ;
        List arr = [value["data"]["banners"] , value["data"]["dynamic"]] ;
        arr.sort() ;
        String d = arr.join("") ;
        var content = new Utf8Encoder().convert(d);
        var digest = md5.convert(content);
        Config().getSpf().setString("schoolMd5", hex.encode(digest.bytes)) ;
      }else{
        Toast.show(value["msg"], context) ;
      }
      setState(() {});
    }) ;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        width: ScreenUtil().setWidth(375) ,
        height:ScreenUtil().setHeight(812) ,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Color.fromARGB(255, 255, 255, 255) ,
              Color.fromARGB(255, 246, 245, 248)
            ] ,
            begin: Alignment.topCenter ,
            end: Alignment.bottomCenter
          )
        ),
        child: Column(
          children: <Widget>[
            Container(
              height:MediaQuery.of(context).padding.top ,
            ) ,
            Expanded(
              child: Container(
                child: ScrollConfiguration(
                  behavior: MyBehavior() ,
                  child: ListView(
                    padding: EdgeInsets.only(top:0),
                    children: <Widget>[
                      Container(
                        width:ScreenUtil().setWidth(375) ,
                        height:33 ,
                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , top:6),
                        child: Text("校园" , style: TextStyle(
                          color: Color.fromARGB(255, 71, 80, 98),
                          fontSize: 26 ,
                          height:1.3 ,
                          fontWeight: FontWeight.bold ,
                          fontFamily: "Alibaba-PuHuiTi-B,Alibaba-PuHuiTi"
                        ),),
                      ) ,
                      Container(
                        width:ScreenUtil().setWidth(345) ,
                        height:ScreenUtil().setHeight(110) ,
                        // 设置圆角无效
                        // decoration: BoxDecoration(
                        //   borderRadius: BorderRadius.all(Radius.circular(20))
                        // ),
                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(16) , right:ScreenUtil().setWidth(15)),
                        child: Swiper(
                          itemCount: list.length ,
                          autoplay: true,
                          scale: 0.9,
                          //loop:false ,
                          itemBuilder: (BuildContext context,int index){
                            // 使用缓存图片类
                            return ClipRRect(
                              borderRadius: BorderRadius.all(Radius.circular(15)),
                              child: GestureDetector(
                                child: CachedNetworkImage(
                                  imageUrl: Config().getImgHost() + list[index]["img"] ,
                                  fit: BoxFit.fill ,
                                  placeholder: (context , url){
                                    return (
                                      Container(
                                        color: Color.fromARGB(255, 246, 245, 248),
                                        child: Center(
                                          child: Image.asset("assets/images/imageloading.png"),
                                        ),
                                      )
                                    ) ;
                                  } ,
                                ),
                                onTap: (){
                                  if(list[index]["type"] == 1){
                                    Navigator.of(context).push(CustomRoute(WebViewByUrl(url: list[index]["url"]))) ;
                                  }
                                },
                              ) 
                            ) ;
                          },
                        )
                      ) ,
                      item("assets/images/miaosha.png", "福利秒杀", "福利卡卷免费领", 34, (){

                      }) ,
                      item("assets/images/around.png", "校园周边", "新店开业优惠信息", 10, (){
                        Navigator.of(context).push(new CustomRoute(AroundPage())) ;
                      }) ,
                      item("assets/images/shangcheng.png", "校园商城", "低价精品等你拿", 10, (){
                        Navigator.of(context).push(new CustomRoute(SchoolMarket())) ;
                      }) ,
                      Container(
                        height: ScreenUtil().setHeight(25),
                        margin: EdgeInsets.only(top:ScreenUtil().setHeight(36) , left:ScreenUtil().setWidth(15)),
                        child: Row(
                          children: <Widget>[
                            Container(
                              child: Text("校园交友" , style: TextStyle(
                                fontSize: ScreenUtil().setSp(18) ,
                                fontWeight: FontWeight.bold ,
                                color:Color.fromARGB(255, 19, 28, 53) ,
                                height:ScreenUtil().setHeight(25) / ScreenUtil().setSp(18) ,
                              ),),
                            ) ,
                            Expanded(
                              child: GestureDetector(
                                child: Container(
                                  height: ScreenUtil().setHeight(18),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.end ,
                                    children: <Widget>[
                                      Container(
                                        height: ScreenUtil().setHeight(18),
                                        margin: EdgeInsets.only(right:ScreenUtil().setWidth(2)),
                                        child: Text(
                                          "查看更多" , style: TextStyle(
                                            color: Color.fromARGB(255, 121, 132, 155) ,
                                            height: ScreenUtil().setHeight(18) / ScreenUtil().setSp(13) ,
                                            fontSize: ScreenUtil().setSp(13)
                                          ),
                                        ),
                                      ) ,
                                      Container(
                                        width: ScreenUtil().setWidth(16),
                                        height: ScreenUtil().setHeight(16),
                                        margin: EdgeInsets.only(right:ScreenUtil().setWidth(15) , bottom: ScreenUtil().setHeight(2) , top:ScreenUtil().setHeight(2)),
                                        child: Image.asset("assets/images/more_2x.png" , fit: BoxFit.fill,),
                                      )
                                    ],
                                  ),
                                ),
                                onTap: (){
                                  Navigator.of(context).push(CustomRoute(SchoolRelation())) ;
                                },
                              )
                            )
                          ],
                        ),
                      ) ,
                      GestureDetector(
                        child: Container(
                          height: ScreenUtil().setHeight(115),
                          width: ScreenUtil().setWidth(345),
                          margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , right:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(18)),
                          decoration: BoxDecoration(
                            color: Colors.white ,
                            borderRadius: BorderRadius.all(Radius.circular(8)) ,
                            boxShadow: [
                              BoxShadow(
                                color: Color.fromARGB(30, 0, 0, 0) ,
                                blurRadius: 2
                              )
                            ]
                          ),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Container(
                                width: ScreenUtil().setWidth(68),
                                child: Container(
                                  width: ScreenUtil().setWidth(40),
                                  height: ScreenUtil().setWidth(40),
                                  margin: EdgeInsets.only(left:ScreenUtil().setWidth(14) , right:ScreenUtil().setWidth(14) , top:ScreenUtil().setHeight(14)),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.all(Radius.circular(ScreenUtil().setWidth(34))),
                                    child: CachedNetworkImage(
                                      imageUrl: Config().getImgHost() + (data == null ? "" : data["icon"]) ,
                                      fit: BoxFit.fill,
                                    ) ,
                                  ),
                                ),
                              ) ,
                              Expanded(
                                child: Container(
                                  margin: EdgeInsets.only(right:ScreenUtil().setWidth(7) , top:ScreenUtil().setHeight(14)),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start ,
                                    children: <Widget>[
                                      Container(
                                        height: ScreenUtil().setHeight(20),
                                        child: Text(data == null ? "" : data["nickname"] , style: TextStyle(
                                          fontSize: ScreenUtil().setSp(14) ,
                                          color: Color.fromARGB(255, 19, 28, 53) ,
                                          fontWeight: FontWeight.bold 
                                        ),),
                                      ) ,
                                      Container(
                                        margin: EdgeInsets.only(top:ScreenUtil().setHeight(7)),
                                        child: Text(data == null ? "" : data["content"] , style: TextStyle(
                                          fontSize: ScreenUtil().setSp(13) ,
                                          color: Color.fromARGB(255, 122, 132, 155) ,
                                        ), overflow: TextOverflow.ellipsis, maxLines: 3,),
                                      )
                                    ],
                                  ),
                                ),
                              )
                            ]
                          ),
                        ),
                        onTap: (){
                          Navigator.of(context).push(CustomRoute(SchoolRelation())) ;
                        },
                      )
                    ],
                  ),
                ),
              )
            )
          ],
        )
      ),
    );
  }

  item(String icon , String title , String sub , int top , var onClick){
    return GestureDetector(
      child: Container(
        height: ScreenUtil().setHeight(80),
        margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , right:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(top)),
        decoration: BoxDecoration(
          color: Colors.white ,
          borderRadius: BorderRadius.all(Radius.circular(13)) ,
          border: Border.all(
            color:Color.fromARGB(255, 236, 237, 241) ,
            style: BorderStyle.solid
          ) ,
          boxShadow: <BoxShadow>[
            BoxShadow(
              color: Color.fromARGB(255, 236, 237, 241),
              offset: Offset(0.0, ScreenUtil().setHeight(4)), //阴影xy轴偏移量
              blurRadius: ScreenUtil().setWidth(12), //阴影模糊程度
              spreadRadius: 1 //阴影扩散程度
            )
          ]
        ) ,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              width: ScreenUtil().setWidth(24),
              height: ScreenUtil().setWidth(24),
              margin: EdgeInsets.only(left:ScreenUtil().setWidth(26)),
              child: Image.asset(icon),
            ) ,
            Expanded(
              child: Container(
                margin: EdgeInsets.only(left:ScreenUtil().setWidth(27)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                      height: ScreenUtil().setHeight(23),
                      margin: EdgeInsets.only(top:ScreenUtil().setHeight(18)),
                      child: Text(title , style: TextStyle(
                        fontSize: ScreenUtil().setSp(16) ,
                        height: ScreenUtil().setHeight(23) / ScreenUtil().setSp(16) ,
                        color: Color.fromARGB(255, 19, 28, 53) ,
                        fontWeight: FontWeight.bold
                      ),),
                    ) ,
                    Container(
                      height: ScreenUtil().setHeight(18),
                      margin: EdgeInsets.only(top:ScreenUtil().setHeight(4)),
                      child: Text(sub , style: TextStyle(
                        fontSize: ScreenUtil().setSp(12) ,
                        height: ScreenUtil().setHeight(18) / ScreenUtil().setSp(12) ,
                        color: Color.fromARGB(255, 121, 132, 155) ,
                        fontWeight: FontWeight.bold
                      ),),
                    )
                  ],
                ),
              )
            ) ,
            Container(
              width: ScreenUtil().setWidth(16),
              height: ScreenUtil().setWidth(16),
              margin: EdgeInsets.only(right:ScreenUtil().setWidth(11)),
              child: Image.asset("assets/images/more_2x.png"),
            )
          ],
        ),
      ),
      onTap: (){
        if(onClick != null){
          onClick() ;
        }
      },
    ) ;
  }
}